package com.mlm.mlmapp.activity;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.mlm.mlmapp.R;
import com.mlm.mlmapp.cons.HTTPCons;
import com.mlm.mlmapp.interfaces.Prefs_;
import com.mlm.mlmapp.utils.CommonUtils;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.CheckedChange;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.StringRes;
import org.androidannotations.annotations.sharedpreferences.Pref;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * Activity which displays a login screen to the user, offering registration as
 * well.
 */
@EActivity(R.layout.login)
public class LoginActivity extends BaseActivity implements HTTPCons {
    AQuery aq;
    AjaxCallback<JSONObject> loginCB;
    AjaxCallback<JSONObject> registerCB;
    AjaxCallback<JSONObject> sendYZMCB;
    @StringRes
    String login_success;
    @Pref
    Prefs_ pref;
    @ViewById
    RelativeLayout login_content_layout;
    @ViewById
    RelativeLayout register_content_layout;
    @ViewById
    Button btn_sendyzm;
    @ViewById
    EditText et_phone;
    @ViewById
    EditText et_pwd;
    @ViewById
    RadioGroup radioGroup;
    @ViewById
    EditText et_yzm;
    @ViewById
    EditText et_registerpwd;
    @ViewById
    EditText et_register_phone;
    @ViewById
    EditText et_nickname;
    @ViewById
    TextView button3;
    @ViewById
    Button button1;
    @Extra
    int flag;
    @Extra
    String collectionid;
    @Extra
    int collectionstatus;
    @Extra
    int index;

    @Click
    void btn_sendyzm() {
        sendYZMAction();
        // set to state to disable

    }

    @Click
    void button1() {
        startActivity(new Intent(this, ForgetpwdActivity_.class));

    }

    @CheckedChange
    void btn_login(CompoundButton btn, Boolean checked) {

        if (checked) {
            login_content_layout.setVisibility(View.VISIBLE);
            register_content_layout.setVisibility(View.GONE);
        }

    }

    @CheckedChange
    void btn_register(CompoundButton btn, Boolean checked) {
        if (checked) {

            login_content_layout.setVisibility(View.GONE);
            register_content_layout.setVisibility(View.VISIBLE);
        }
    }

    @Click
    void btn_login_action() {

        if (loginValidateEmpty()) {
            loginAction();
        }

    }

    @Click
    void btn_register_action() {
        if (registerValidateEmpty()) {
            registerAction();
        }

    }

    @AfterViews
    void init() {
        String title = getTitle().toString();
        button3.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);//
        final String url = "http://img.mlmsalon.com/registration.pdf";
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//				Intent intent=new Intent();
//				intent.putExtra("url","http://docs.google.com/gview?embedded=true&url="+url );
//				intent.setClass(LoginActivity.this, ShowWebView_.class);
//				startActivity(intent);
                PDFActivity_.intent(LoginActivity.this).start();
            }
        });

        if (!"".equals(title)) {
            ((TextView) this.findViewById(R.id.tv_title)).setText(title);
        }

        aq = new AQuery(this);
        loginCB = new AjaxCallback<JSONObject>() {

            @Override
            public void callback(String url, JSONObject html, AjaxStatus status) {
                if (status.getCode() == -101) {
                    Toast.makeText(aq.getContext(), "网络异常,请检查网络",
                            Toast.LENGTH_SHORT);
                    return;
                }
                if (status.getCode() != 200) {
                    Toast.makeText(aq.getContext(), "网络异常:" + status.getCode(),
                            Toast.LENGTH_LONG).show();
                } else {
                    try {
                        if (html.getBoolean("isSuccess")) {
                            pref.edit().loginID().put(tempMobile).apply();
                            Toast.makeText(aq.getContext(), "登录成功",
                                    Toast.LENGTH_LONG).show();
                            onSuccess();

                        } else {
                            Toast.makeText(aq.getContext(),
                                    html.getString("errors"), Toast.LENGTH_LONG)
                                    .show();
                        }
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
            }
        };
        registerCB = new AjaxCallback<JSONObject>() {

            @Override
            public void callback(String url, JSONObject html, AjaxStatus status) {
                if (status.getCode() == -101) {
                    Toast.makeText(LoginActivity.this, "网络异常,请检查网络",
                            Toast.LENGTH_SHORT);
                    return;
                }
                if (status.getCode() != 200) {
                    Toast.makeText(aq.getContext(), "网络异常:" + status.getCode(),
                            Toast.LENGTH_LONG).show();
                } else {
                    try {
                        if (html.getBoolean("isSuccess")) {
                            pref.edit().loginID().put(tempMobile).apply();
                            Toast.makeText(aq.getContext(), "注册成功",
                                    Toast.LENGTH_LONG).show();
                            onSuccess();

                        } else {
                            Toast.makeText(aq.getContext(),
                                    html.getString("errors"), Toast.LENGTH_LONG)
                                    .show();
                        }
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
            }
        };
        sendYZMCB = new AjaxCallback<JSONObject>() {

            @Override
            public void callback(String url, JSONObject html, AjaxStatus status) {
                if (status.getCode() == -101) {
                    Toast.makeText(LoginActivity.this, "网络异常,请检查网络",
                            Toast.LENGTH_SHORT);
                    return;
                }
                if (status.getCode() != 200) {
                    Toast.makeText(aq.getContext(), "网络异常:" + status.getCode(),
                            Toast.LENGTH_LONG).show();
                } else {
                    try {
                        if (html.getBoolean("isSuccess")) {

                            Toast.makeText(aq.getContext(), "发送成功",
                                    Toast.LENGTH_LONG).show();
                            // MainActivity_.intent(LoginActivity.this).start();
                            btn_sendyzm.setClickable(false);
                            btn_sendyzm
                                    .setBackgroundResource(R.drawable.grey_edge_btn);
                            btn_sendyzm.setTextColor(Color
                                    .parseColor("#d0d0d0"));
                            CountDownTimer timer = new CountDownTimer(period,
                                    step) {

                                @Override
                                public void onTick(long arg0) {
                                    // TODO Auto-generated method stub

                                    // tick tick tick...

                                    btn_sendyzm.setText(getString(
                                            R.string.hint_reg_waityzm,
                                            arg0 / 1000));

                                }

                                @Override
                                public void onFinish() {
                                    // TODO Auto-generated method stub
                                    // get back to normal
                                    btn_sendyzm.setClickable(true);
                                    btn_sendyzm.setTextColor(Color
                                            .parseColor("#ea2626"));
                                    btn_sendyzm
                                            .setText(R.string.hint_reg_sendyzm);
                                    btn_sendyzm
                                            .setBackgroundResource(R.drawable.red_edge_btn);

                                }
                            };
                            timer.start();
                        } else {
                            Toast.makeText(aq.getContext(),
                                    html.getString("errors"), Toast.LENGTH_LONG)
                                    .show();
                        }
                    } catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
            }
        };
    }

    /**
     * send sms authcode request
     *
     * @throws UnsupportedEncodingException
     */
    private void sendYZMAction() {
        String mobile = et_register_phone.getText().toString().trim();
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        if (CommonUtils.isMobileNO(mobile)) {
            pairs.add(new BasicNameValuePair("mobile", mobile));
            pairs.add(new BasicNameValuePair("type", AUTH_CODE_REGISTER));
            CommonUtils.postRequest(sendyzm_action, aq, sendYZMCB, pairs);
        } else {
            Toast.makeText(LoginActivity.this, "手机号格式不正确", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * login request
     *
     * @throws UnsupportedEncodingException
     */
    private void loginAction() {
        String account = et_phone.getText().toString().trim();
        String pwd = et_pwd.getText().toString().trim();
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        if (CommonUtils.isMobileNO(account)) {
            pairs.add(new BasicNameValuePair("mobile", account));
            tempMobile = account;
            if (CommonUtils.isCorrectUserPwd(pwd)) {
                    pairs.add(new BasicNameValuePair("passwd", pwd));
                    CommonUtils.postRequest(login_action, aq, loginCB, pairs);

            } else {
                Toast.makeText(LoginActivity.this, "密码必须为6-16位英文字母与数字的组合", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(LoginActivity.this, "手机号格式不正确", Toast.LENGTH_SHORT).show();
        }


    }

    /**
     * Register request
     *
     * @throws UnsupportedEncodingException
     */
    private void registerAction() {
        String mobile = et_register_phone.getText().toString().trim();
        String passwd = et_registerpwd.getText().toString().trim();
        String authcode = et_yzm.getText().toString().trim();
        String username = et_nickname.getText().toString().trim();
        String sexy = "";
        int sexFlag = radioGroup.getCheckedRadioButtonId();

        RadioButton rad_btn = (RadioButton) this.findViewById(sexFlag);
        if ("男".equals(rad_btn.getText())) {
            sexy = "1";
        } else {
            sexy = "2";
        }

        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        if (CommonUtils.isMobileNO(mobile)) {
            pairs.add(new BasicNameValuePair("username", username));
            pairs.add(new BasicNameValuePair("sexy", sexy));
            pairs.add(new BasicNameValuePair("mobile", mobile));
            pairs.add(new BasicNameValuePair("authcode", authcode));
            if (CommonUtils.isCorrectUserPwd(passwd)) {
                    pairs.add(new BasicNameValuePair("passwd", passwd));
                    CommonUtils.postRequest(register_action, aq, registerCB, pairs);
                    tempMobile = mobile;

            } else {
                Toast.makeText(LoginActivity.this, "密码必须为6-16位英文字母与数字的组合", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(LoginActivity.this, "手机号格式不正确", Toast.LENGTH_SHORT).show();
        }

    }

    // save the mobile temporarily ,if login successful ,save into the sp,for
    // keeping the login state
    private String tempMobile = "";

    public boolean loginValidateEmpty() {
        List<View> validateList = new ArrayList<View>();
        et_phone.setTag("phone");
        validateList.add(et_phone);
        validateList.add(et_pwd);
        return CommonUtils.validateETEmpty(this, validateList);
    }

    public boolean registerValidateEmpty() {
        List<View> validateList = new ArrayList<View>();
        et_register_phone.setTag("phone");
        validateList.add(et_register_phone);
        validateList.add(et_registerpwd);
        validateList.add(et_nickname);
        validateList.add(et_yzm);
        return CommonUtils.validateETEmpty(this, validateList);
    }

    void onSuccess() {
        index = getIntent().getIntExtra("index", -1);
        Intent intent = this.getIntent();
        intent.putExtra("flag", true);
        intent.putExtra("collectionid", collectionid);
        intent.putExtra("collectionstatus", collectionstatus);
        intent.putExtra("collectionstatus", index);
        if (index != -1) {
            this.setResult(HairDresserDetailActivity.RESULT_STYLE_COLLECTION, intent);
        } else {
            this.setResult(HairDresserDetailActivity.RESULT_DRESSER_COLLECTION, intent);
        }

        this.finish();

    }

    @Click
    void btn_back() {
        onBackPressed();
    }

    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        Intent intent = new Intent();
        this.setResult(RESULT_CANCELED, intent);
        this.finish();
    }
}
